//
//  SongSheetController.m
//  Kugou-OC
//
//  Created by BH on 16/5/27.
//  Copyright © 2016年 Sunny. All rights reserved.
//

#import "SongSheetController.h"
#import "GlobalDefine.h"
#import "SongSheetCell.h"
#import "NetworkHelper.h"
#import "SongSheetModel.h"
#import <SDAutoLayout/UIView+SDAutoLayout.h>
#import <MJRefresh/MJRefresh.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import <MBProgressHUD/MBProgressHUD.h>

@interface CollectionHeaderView : UICollectionReusableView

@end

@implementation CollectionHeaderView

-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        UIButton *allCategoryBtn = ALLOC(UIButton);
        allCategoryBtn.layer.borderWidth = 1;
        allCategoryBtn.layer.borderColor = BG_COLOR.CGColor;
        [allCategoryBtn setTitle:@"全部分类" forState:UIControlStateNormal];
        [allCategoryBtn setTitleColor:BG_COLOR forState:UIControlStateNormal];
        allCategoryBtn.titleLabel.font = TITLE_FOUR_FONT;
        allCategoryBtn.sd_cornerRadiusFromWidthRatio = @(0.1);
        
        UIButton *recommendBtn = ALLOC(UIButton);
        [recommendBtn setTitleColor:BG_COLOR forState:UIControlStateSelected];
        [recommendBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [recommendBtn setTitle:@"推荐" forState:UIControlStateNormal];
        recommendBtn.titleLabel.font = TITLE_FOUR_FONT;
        recommendBtn.selected = YES;
        
        UIImageView *sepratorLine = ALLOC(UIImageView);
        sepratorLine.image = IMAGE(@"line_short_bold_vertical");
        
        UIButton *recentlyBtn = ALLOC(UIButton);
        [recentlyBtn setTitle:@"最新" forState:UIControlStateNormal];
        [recentlyBtn setTitleColor:BG_COLOR forState:UIControlStateSelected];
        [recentlyBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        recentlyBtn.titleLabel.font = TITLE_FOUR_FONT;
        
        [self sd_addSubviews:@[allCategoryBtn,recentlyBtn,recommendBtn,sepratorLine]];
        
        allCategoryBtn.sd_layout.leftSpaceToView(self,15).topSpaceToView(self,8).bottomSpaceToView(self,8).widthIs(80);
        recentlyBtn.sd_layout.rightSpaceToView(self,10).topEqualToView(allCategoryBtn).bottomEqualToView(allCategoryBtn).widthIs(50);
        sepratorLine.sd_layout.rightSpaceToView(recentlyBtn,0).topSpaceToView(self,15).bottomSpaceToView(self,15).widthIs(1);
        recommendBtn.sd_layout.rightSpaceToView(sepratorLine,0).topEqualToView(recentlyBtn).bottomEqualToView(recentlyBtn).widthIs(50);
    }
    
    return self;
}

@end

@interface SongSheetController ()<UICollectionViewDataSource,UICollectionViewDelegate>
{
    NSInteger page;
}

@property(nonatomic,strong)UICollectionView *collectView;
@property(nonatomic,strong)CollectionHeaderView *collectHeader;
@property(nonatomic,strong)NSMutableArray *dataArray;

@end

@implementation SongSheetController

-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        self.dataArray = [NSMutableArray array];
    }
    
    return _dataArray;
}

-(id)init{
    self = [super init];
    if (self) {
        page = 1;
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.collectView];
    
    _collectHeader = [[CollectionHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
    
    self.collectView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    [self getData];
}

-(UICollectionView *)collectView{
    if (_collectView == nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.headerReferenceSize = CGSizeMake(SCREEN_WIDTH, 44);
        _collectView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) collectionViewLayout:layout];
        
        //collectView 每个item的size
        layout.itemSize = CGSizeMake((SCREEN_WIDTH-45)/2, (SCREEN_WIDTH-45)/2+50);
        //item的横向间距
        layout.minimumLineSpacing = 5;
        //item的纵向间距
        layout.minimumInteritemSpacing = 0;
        //边距
        layout.sectionInset = UIEdgeInsetsMake(0, 15, 5, 15);
        
        //注册cell
        [_collectView registerClass:[SongSheetCell class] forCellWithReuseIdentifier:@"SongSheetCell"];
        //注册headerView
        [_collectView registerClass:[CollectionHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ReusableView"];
        _collectView.dataSource = self;
        _collectView.delegate = self;
        //自适应大小
        _collectView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        
        _collectView.backgroundColor = [UIColor whiteColor];
    }
    
    return _collectView;
}

-(void)getData{
    
    NSString *urlStr = @"http://ioscdn.kugou.com/api/v3/category/special";
    NSDictionary *params = @{@"categoryid":@"0",@"page":@(page),@"pagesize":@"12",@"sort":@"3"};
    [[NetworkHelper shareNetwork] getDataWithUrl:urlStr params:params view:(page==1?self.view:nil) success:^(id response) {
        
        if ([response[@"status"] isEqual:@(1)]) {
            NSArray *array = response[@"data"][@"info"];
            NSMutableArray *tempArray = [NSMutableArray array];
            for (NSDictionary *dict in array) {
                SongSheetModel *model = [[SongSheetModel alloc] initWithDict:dict];
                [tempArray addObject:model];
            }
            
            [self.dataArray addObjectsFromArray:tempArray];
            [self.collectView reloadData];
        }else{
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            
            // Configure for text only and offset down
            hud.mode = MBProgressHUDModeText;
            hud.labelText = @"Some message...";
            hud.margin = 10.f;
            hud.yOffset = 150.f;
            hud.removeFromSuperViewOnHide = YES;
            
            [hud hide:YES afterDelay:3];
        }
        
        [self.collectView.mj_footer endRefreshing];
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error.localizedDescription);
    }];
}

/**
 *  上拉加载更多
 */
-(void)loadMoreData{
    page++;
    [self getData];
}

#pragma mark - UICollectionView datasource & delegate
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"SongSheetCell";
    SongSheetCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    
    SongSheetModel *model = self.dataArray[indexPath.row];
    [cell.iconImg sd_setImageWithURL:[NSURL URLWithString:model.imgurl] placeholderImage:IMAGE(@"collectionview_placeholdimg")];
    cell.titleLab.text = model.specialname;
    cell.playcountLab.text = [self integerToString:model.playcount];
    
    return cell;
}

//UICollection header view
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ReusableView" forIndexPath:indexPath ];
    
    [headerView addSubview:_collectHeader];
    
    return headerView;
}

//数值转换
-(NSString *)integerToString:(NSInteger)value{
    NSString *string;
    
    if (value>=10000) {

        string = [NSString stringWithFormat:@"%.1f万",value/10000.0];
    }else{
        string = [NSString stringWithFormat:@"%ld",value];
    }
    
    return string;
}

@end
